//
//  JPVideoPlayerWBControlBar.m
//  JPVideoPlayerDemo
//
//  Created by xin on 2018/4/13.
//  Copyright © 2018年 NewPan. All rights reserved.
//

#import "JPVideoPlayerWBControlBar.h"
#import "UIView+WebVideoCache.h"
#import "JPVideoPlayerControlViews.h"

@interface JPVideoPlayerWBControlBar()<JPVideoPlayerProtocol>

@property (nonatomic, strong) UILabel *startTimeLabel;

@property (nonatomic, strong) UILabel *totalTimeLabel;

@property (nonatomic, strong) UIView<JPVideoPlayerControlProgressProtocol> *progressView;

@property (nonatomic, strong) UIButton *landscapeButton;

@property (nonatomic, weak) UIView *playerView;

@property(nonatomic, assign) NSTimeInterval totalSeconds;

@end

static const CGFloat kJPVideoPlayerWBControlBarPlayerButtonWidthHeight = 54;
static const CGFloat kJPVideoPlayerWBControlBarLandScapeButtonWidthHeight = 22;
static const CGFloat kJPVideoPlayerWBControlBarTimeLabelWidth = 36;
static const CGFloat kJPVideoPlayerWBControlBarTimeLabelHeight = 22;
static const CGFloat kJPVideoPlayerWBControlBarElementGap = 16;

@implementation JPVideoPlayerWBControlBar

- (void)dealloc {
    //移除观察的key
    [self.progressView removeObserver:self forKeyPath:@"userDragTimeInterval"];
}

- (instancetype)initWithFrame:(CGRect)frame {
    NSAssert(NO, @"Please use given method to initialize this class.");
    return [self initWithProgressView:nil];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    NSAssert(NO, @"Please use given method to initialize this class.");
    return [self initWithProgressView:nil];
}

- (instancetype)initWithProgressView:(UIView<JPVideoPlayerControlProgressProtocol> *_Nullable)progressView
{
    self = [super initWithFrame:CGRectZero];
    if (self) {
        _progressView = progressView;
        [self _setup];
    }
    return self;
}

- (instancetype)init {
    NSAssert(NO, @"Please use given method to initialize this class.");
    return [self initWithProgressView:nil];
}

#pragma mark - JPVideoPlayerLayoutProtocol
- (void)layoutThatFits:(CGRect)constrainedRect
nearestViewControllerInViewTree:(UIViewController *_Nullable)nearestViewController
  interfaceOrientation:(JPVideoPlayViewInterfaceOrientation)interfaceOrientation
{
    CGSize referenceSize = constrainedRect.size;
    CGFloat elementOriginY = (referenceSize.height - kJPVideoPlayerWBControlBarElementGap) * 0.5;

    self.startTimeLabel.frame = CGRectMake(kJPVideoPlayerWBControlBarElementGap, elementOriginY, kJPVideoPlayerWBControlBarTimeLabelWidth, kJPVideoPlayerWBControlBarTimeLabelHeight);
    self.landscapeButton.frame = CGRectMake(referenceSize.width - kJPVideoPlayerWBControlBarElementGap - kJPVideoPlayerWBControlBarLandScapeButtonWidthHeight,
                                            elementOriginY,
                                            kJPVideoPlayerWBControlBarLandScapeButtonWidthHeight,
                                            kJPVideoPlayerWBControlBarLandScapeButtonWidthHeight);
    CGFloat totalTimeLabelOriginX = self.landscapeButton.frame.origin.x - kJPVideoPlayerWBControlBarElementGap - kJPVideoPlayerWBControlBarTimeLabelWidth;
    self.totalTimeLabel.frame = CGRectMake(totalTimeLabelOriginX, elementOriginY, kJPVideoPlayerWBControlBarTimeLabelWidth, kJPVideoPlayerWBControlBarTimeLabelHeight);
    CGFloat progressViewOriginX = CGRectGetMaxX( self.startTimeLabel.frame) + kJPVideoPlayerWBControlBarElementGap;
    CGFloat progressViewWidth = self.totalTimeLabel.frame.origin.x - progressViewOriginX - kJPVideoPlayerWBControlBarElementGap;
    self.progressView.frame = CGRectMake(progressViewOriginX,
                                         elementOriginY,
                                         progressViewWidth,
                                         kJPVideoPlayerWBControlBarLandScapeButtonWidthHeight);
    if([self.progressView respondsToSelector:@selector(layoutThatFits:nearestViewControllerInViewTree:interfaceOrientation:)]){
        [self.progressView layoutThatFits:self.progressView.bounds
          nearestViewControllerInViewTree:nearestViewController
                     interfaceOrientation:interfaceOrientation];
    }
}

#pragma mark - JPVideoPlayerProtocol

- (void)viewWillAddToSuperView:(UIView *)view {
    self.playerView = view;
    [self updateTimeLabelWithElapsedSeconds:0 totalSeconds:0];
    [self.progressView viewWillAddToSuperView:view];
}

- (void)viewWillPrepareToReuse {
    [self updateTimeLabelWithElapsedSeconds:0 totalSeconds:0];
    [self.progressView viewWillPrepareToReuse];
}

- (void)cacheRangeDidChange:(NSArray<NSValue *> *)cacheRanges {
    [self.progressView cacheRangeDidChange:cacheRanges];
}

- (void)playProgressDidChangeElapsedSeconds:(NSTimeInterval)elapsedSeconds
                               totalSeconds:(NSTimeInterval)totalSeconds {
    self.totalSeconds = totalSeconds;
    if(!self.progressView.userDragging){
        [self updateTimeLabelWithElapsedSeconds:elapsedSeconds totalSeconds:totalSeconds];
    }
    [self.progressView playProgressDidChangeElapsedSeconds:elapsedSeconds
                                              totalSeconds:totalSeconds];
}

- (void)didFetchVideoFileLength:(NSUInteger)videoLength {
    [self.progressView didFetchVideoFileLength:videoLength];
}

- (void)videoPlayerStatusDidChange:(JPVideoPlayerStatus)playerStatus {
//    BOOL isPlaying = playerStatus == JPVideoPlayerStatusBuffering || playerStatus == JPVideoPlayerStatusPlaying;
//    self.playButton.selected = !isPlaying;
}

- (void)videoPlayerInterfaceOrientationDidChange:(JPVideoPlayViewInterfaceOrientation)interfaceOrientation {
    self.landscapeButton.selected = interfaceOrientation == JPVideoPlayViewInterfaceOrientationLandscape;
}

#pragma mark - Private

- (void)updateTimeLabelWithElapsedSeconds:(NSTimeInterval)elapsedSeconds
                             totalSeconds:(NSTimeInterval)totalSeconds {
    NSString *elapsedString = [self convertSecondsToTimeString:elapsedSeconds];
    NSString *totalString = [self convertSecondsToTimeString:totalSeconds];
    self.startTimeLabel.attributedText = [[NSAttributedString alloc] initWithString:elapsedString
                                                                    attributes:@{
                                                                                 NSFontAttributeName : [UIFont systemFontOfSize:12],
                                                                                 NSForegroundColorAttributeName : [UIColor whiteColor]
                                                                                 }];
    
    self.totalTimeLabel.attributedText = [[NSAttributedString alloc] initWithString:totalString
                                                                         attributes:@{
                                                                                      NSFontAttributeName : [UIFont systemFontOfSize:12],
                                                                                      NSForegroundColorAttributeName : [UIColor whiteColor]
                                                                                      }];
}

- (NSString *)convertSecondsToTimeString:(NSTimeInterval)seconds {
    NSUInteger minute = (NSUInteger)(seconds / 60);
    NSUInteger second = (NSUInteger)((NSUInteger)seconds % 60);
    return [NSString stringWithFormat:@"%02d:%02d", (int)minute, (int)second];
}

- (void)landscapeButtonDidClick:(UIButton *)button {
    button.selected = !button.selected;
    self.playerView.jp_viewInterfaceOrientation == JPVideoPlayViewInterfaceOrientationPortrait ? [self.playerView jp_gotoLandscape] : [self.playerView jp_gotoPortrait];
}

- (void)_setup {
    self.backgroundColor = [UIColor clearColor];
    
    if(!self.progressView){
        self.progressView = ({
            JPVideoPlayerControlProgressView *view = [JPVideoPlayerControlProgressView new];
            [view addObserver:self forKeyPath:@"userDragTimeInterval" options:NSKeyValueObservingOptionNew context:nil];
            [self addSubview:view];
            
            view;
        });
    }
    
    self.startTimeLabel = ({
        UILabel *label = [UILabel new];
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
        
        label;
    });
    
    self.totalTimeLabel = ({
        UILabel *label = [UILabel new];
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
        
        label;
    });
    
    self.landscapeButton = ({
        UIButton *button = [UIButton new];
        [button setImage:[UIImage imageNamed:@"JPVideoPlayer.bundle/jp_videoplayer_landscape"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"JPVideoPlayer.bundle/jp_videoplayer_portrait"] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(landscapeButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        
        button;
    });
}

- (void)observeValueForKeyPath:(nullable NSString *)keyPath
                      ofObject:(nullable id)object
                        change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change
                       context:(nullable void *)context {
    if([keyPath isEqualToString:@"userDragTimeInterval"]) {
        NSNumber *timeIntervalNumber = change[NSKeyValueChangeNewKey];
        NSTimeInterval timeInterval = timeIntervalNumber.floatValue;
        [self updateTimeLabelWithElapsedSeconds:timeInterval totalSeconds:self.totalSeconds];
    }
}

@end
